package cn.itcast.tlias.com.tliaswork.filter;

import cn.itcast.tlias.com.tliaswork.pojo.Result;
import cn.itcast.tlias.com.tliaswork.utils.JWTUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.TextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //只会被调用一次 ctrl+o是快捷键
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String uri = req.getRequestURL().toString();
        //        //1.获取请求的Url
//        HttpServletRequest req = (HttpServletRequest) request;
//        HttpServletResponse resp = (HttpServletResponse) response;
//        String uri = req.getRequestURL().toString();
//        log.info("请求的URL是{}", uri);
//        //2,判断Url中是否包含login,如果包含,说明是登录操作
//        if (uri.contains("login")) {
//            log.info("登录操作放行");
//            //2.1.放行
//            chain.doFilter(request, response);
//        } else {
//            //3,获取token令牌
//            String token = req.getHeader("token");
//            //4,判断token令牌是否是否存在
//            if (TextUtils.isEmpty(token)) {
//                log.info("请求头的token,返回未登录的类型");
//                Result error = Result.error("NOT_LOGIN");
//                //手动的转换
//                String errorJson = JSONObject.toJSONString(error);
//
//                //设置中文不乱吗
//                resp.setContentType("text/html;charset=utf-8");
//                //返回中文字符串
//                resp.getWriter().write(errorJson);
//
//            }else {
//                log.info("请求头的token有值");
//                //5解析token值,如果解析失败,返回错误结果
//                boolean expire = JWTUtils.isExpire(token);
//                if (expire){
//                    //6,放行
//                    chain.doFilter(request, response);
//                }else {
//                    //如果令牌出错也需要返回错误信息
//                    Result error = Result.error("NOT_LOGIN");
//                    //手动的转换
//                    String errorJson = JSONObject.toJSONString(error);
//
//                    //设置中文不乱吗
//                    resp.setContentType("text/html;charset=utf-8");
//                    //返回中文字符串
//                    resp.getWriter().write(errorJson);
//                }
//            }
//        }

        chain.doFilter(request, response);
    }
    //只会被调用一次
    @Override
    public void destroy() {

    }
}
